package translate;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import entity.IpSocket;

public class YahooTranslator {
	public static String translate(String text, String sourceLanguage,
			String toLanguage) {
		try {
			Document doc = null;
			IpSocket ipSocket = new IpSocket();
			Random random = new Random();
			Socket socket = new Socket("babelfish.yahoo.com", 80,
					InetAddress.getByName(ipSocket.get()),
					random.nextInt(1000) + 30000);
			// Socket socket = new Socket("babelfish.yahoo.com", 80);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));

			writer.write("GET "
					+ "http://babelfish.yahoo.com/translate_txt?trtext="
					+ encodeURIcomponent(text) + "&lp=" + sourceLanguage + "_"
					+ toLanguage + " HTTP/1.1\r\n");
			writer.write("Host: " + "www." + "babelfish.yahoo.com" + "\r\n");
			writer.write("Referer: http://5ty.org\r\n");
			writer.write("User-Agent:	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1\r\n");
			writer.write("Accept-Language:	en-us,en;q=0.5\r\n");
			writer.write("Accept-Encoding:	gzip, deflate\r\n");
			writer.write("Accept-Charset:	ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n");
			writer.write("Connection:	Close\r\n");
			writer.write("\r\n\r\n");
			writer.flush();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream(), "UTF-8"));
			String content = "";
			while (true) {
				String str = reader.readLine();
				if (str == null)
					break;
				content += str;
			}
			doc = Jsoup.parse(content);
			reader.close();
			writer.close();
			socket.close();
			if (doc.getElementById("result") != null) {
				return doc.getElementById("result").text();
			}
			return text;
		} catch (Exception e) {
			return text;
		}
	}

	public static String encodeURIcomponent(String s) {
		StringBuilder o = new StringBuilder();
		for (char ch : s.toCharArray()) {
			if (isUnsafe(ch)) {
				o.append('%');
				o.append(toHex(ch / 16));
				o.append(toHex(ch % 16));
			} else
				o.append(ch);
		}
		return o.toString();
	}

	private static char toHex(int ch) {
		return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
	}

	private static boolean isUnsafe(char ch) {
		if (ch > 128 || ch < 0)
			return true;
		return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
	}
}
